package edu.ccut.saturn.manager.bundles.core;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.component.ComponentManager;
import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IComponentInfo;
import edu.ccut.saturn.component.IParameterContext;
import edu.ccut.saturn.component.IParameterInfo;
import edu.ccut.saturn.component.IValidateInfo;
import edu.ccut.saturn.component.IValidateUseInfo;
import edu.ccut.saturn.component.impl.SaturnLogicComponentInfo;
import edu.ccut.saturn.component.xml.XMLHelper;
import edu.ccut.saturn.manager.bundles.core.Activator;

public class DeleteValidate extends DefaultComponent {
	@Override
	public void execute(IParameterContext parameterContext) throws Exception {

		String fullKey = (String) parameterContext.getParameterValue(0);
		String nodeId = (String) parameterContext.getParameterValue(1);
		String paramId = (String) parameterContext.getParameterValue(2);
		String validateInfoFullKey = (String) parameterContext
				.getParameterValue(3);	
		
		IComponentInfo componentInfo = ComponentManager.getInstance()
				.getComponentInfo(fullKey);
		List<IParameterInfo> paramInfos = ((SaturnLogicComponentInfo) componentInfo)
				.getNodeInfo(nodeId).getParameterInfos();
		IParameterInfo paramInfo = paramInfos
				.get(Integer.parseInt(paramId) - 1);
		IValidateUseInfo validateUse = paramInfo.getValidateUses();
		
		List<IValidateInfo> validateList = new ArrayList<IValidateInfo>();
		
		if (validateUse != null) {
			validateList = validateUse.getValidateInfos();
		}

		for (IValidateInfo validateInfo : validateList) {
			if (validateInfo.getValidateInfoFullkey().equals(
					validateInfoFullKey)) {
				validateList.remove(validateInfo);
				break;
			}
		}
		this.createPachFileByComponentInfo(fullKey, componentInfo);
	}
	

	private void createPachFileByComponentInfo(String fullKey, IComponentInfo componentInfo) throws IOException {
		// 将componentInfo生成文件
		String dir = Activator.getServerLocation() + File.separator + "patch"
				+ File.separator;
		// "c:" + File.separator + "patch" + File.separator;
		String directPath = (fullKey.substring(0, fullKey.lastIndexOf("/")))
				.replaceAll("/", File.separator + File.separator);
		String directPathTransformed = (dir + directPath).replaceAll("::", "")
				+ File.separator;
		String componentFileName = (fullKey.substring(fullKey.lastIndexOf("/")))
				.replace("/", "");

		XMLHelper.writeFile(directPathTransformed, componentFileName,
				componentInfo.toXmlStr());
	}
	
}